package com.city.parking.provider;

import java.util.ArrayList;
import java.util.List;

import com.city.parking.util.SharePrefUtil;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.BaseColumns;
import android.util.Log;

public class ParkingProviderHelper {
	public static final Uri BASE_URI = Uri.parse("content://"
			+ ParkingProvider.AUTHORITY);
	public static final String DEFAULT_SORT_ORDER = " _id";
    private static String owner = SharePrefUtil.getUsrId();

    public static class Parking implements BaseColumns {
        public static final Uri CONTENT_URI = Uri.withAppendedPath(BASE_URI, "/parkings");
        // Parking
        public static final String COLUMN_LONGITUDE = "longitude";
        public static final String COLUMN_LATITUDE = "latitude";
        public static final String COLUMN_ADDR = "addr";
        public static final String COLUMN_NAME = "name";
        public static final String COLUMN_OWN = "own";
    }

    public static class Car implements BaseColumns {
        public static final Uri CONTENT_URI = Uri.withAppendedPath(BASE_URI, "/cars");
        public static final String COLUMN_OWNER = "owner";
        public static final String COLUMN_NO = "no";
        public static final String COLUMN_ISDEFAULT = "def";
        public static final String COLUMN_ISBIG = "big";
    }
	

	public static int addCar(Context context, String no, int big, int dft) {
	    int result = 0;
        log("addCar " + no);
	    ContentValues cv = new ContentValues();
	    cv.put(Car.COLUMN_OWNER, owner);
        cv.put(Car.COLUMN_NO, no);
        cv.put(Car.COLUMN_ISBIG, big);
        cv.put(Car.COLUMN_ISDEFAULT, dft);
        ContentResolver resolver = context.getContentResolver();
        
        Cursor cursor = null;
        try {
            String condition = Car.COLUMN_NO + "=? and " + Car.COLUMN_OWNER + "=?";
            String[] conditionArgs = new String[] {
            	no, owner
            };
            cursor = resolver.query(Car.CONTENT_URI, null, condition, conditionArgs, null);
            if (cursor != null && cursor.moveToFirst()) {
                result = -2;
            } else {
                resolver.insert(Car.CONTENT_URI, cv);
            }
        } catch (Exception e) {
            e.printStackTrace();
            result = -1;
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
        return result;
	}

	public static int setDefault(Context context, String no) {
        log("getAllCar");
	    int result = 0;
        ContentResolver resolver = context.getContentResolver();

        try {
        	// clear old
    	    ContentValues cv = new ContentValues();
    	    cv.put(Car.COLUMN_ISDEFAULT, 0);
            String condition = Car.COLUMN_OWNER + "=? and " + Car.COLUMN_ISDEFAULT + "=?";
			String[] conditionArgs = new String[] { owner, "1"};
            resolver.update(Car.CONTENT_URI, cv, condition, conditionArgs);
    	    
            // set new
            cv.put(Car.COLUMN_ISDEFAULT, 1);
            condition = Car.COLUMN_NO + "=? and " + Car.COLUMN_OWNER + "=?";
			conditionArgs = new String[] { no, owner };
			result = resolver.update(Car.CONTENT_URI, cv, condition, conditionArgs);
        } catch (Exception e) {
            e.printStackTrace();
            result = -1;
        }

        return result;
	}

    public static Cursor getDftCar(Context context) {
        log("getAllCar");
        ContentResolver resolver = context.getContentResolver();
        Cursor cursor = null;
        try {
            String condition = Car.COLUMN_OWNER + "=? and " + Car.COLUMN_ISDEFAULT + "=?";
			String[] conditionArgs = new String[] { owner, "1"};
            cursor = resolver.query(Car.CONTENT_URI, null, condition, conditionArgs, DEFAULT_SORT_ORDER);
            if (cursor != null && cursor.moveToFirst()) {
                return cursor;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    public static Cursor getAllCars(Context context) {
        log("getAllCars");
        ContentResolver resolver = context.getContentResolver();
        Cursor cursor = null;
        try {
            cursor = resolver.query(Car.CONTENT_URI, null, Car.COLUMN_OWNER + "=?", 
            		new String[] {owner}, DEFAULT_SORT_ORDER);
            if (cursor != null && cursor.moveToFirst()) {
                return cursor;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }
	
    public static int delCar(Context context, String owner, String no) {
        log("delCar " + no);
        String where = Car.COLUMN_NO + "=" + no + " and "
                + Car.COLUMN_OWNER + "=" + owner;

        ContentResolver resolver = context.getContentResolver();
        return resolver.delete(Car.CONTENT_URI, where, null);
    }
    
	public static int addParking(Context context, ParkingRecord parking) {
	    int result = -1;
        log("add parking ");
	    ContentValues cv = toContentValues(parking);
        ContentResolver resolver = context.getContentResolver();
        
        Cursor cursor = null;
        try {
            String condition = Parking.COLUMN_NAME + "=?";
            String[] conditionArgs = new String[] {
            	parking.name
            };
            cursor = resolver.query(Parking.CONTENT_URI, null, condition, conditionArgs, null);
            if (cursor != null && cursor.moveToFirst()) {
                result = -2;
            } else {
                if (null != resolver.insert(Parking.CONTENT_URI, cv)) {
                	result = 0;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            result = -1;
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
        return result;
	}

    public static void updateParking(Context context, ParkingRecord parking) {
        log("updateDevice " + parking.addr);
        ContentValues cv = toContentValues(parking);
        context.getContentResolver().update(Parking.CONTENT_URI, cv, 
        		"longitude=? and latitude=?", new String[] { parking.longitude+"", parking.latitude+"" });
    }

	public static int clearAll(Context context) {
		log("delAllParkings");
		ContentResolver resolver = context.getContentResolver();
		return resolver.delete(Parking.CONTENT_URI, null, null);
	}
	
    public static int delParkingByAddr(Context context, String addr) {
        log("delParkingByAddr " + addr);
        ContentResolver resolver = context.getContentResolver();
        int ret = -1;
        try {
            ret = resolver.delete(Parking.CONTENT_URI, "addr=?", new String[] { addr });
        } catch (Exception e) {
            e.printStackTrace();
        }

        return ret;
    }
    
    public static int delParkingByName(Context context, String name) {
        log("delParkingByName " + name);
        ContentResolver resolver = context.getContentResolver();
        int ret = -1;
        try {
            ret = resolver.delete(Parking.CONTENT_URI, "name=?", new String[] { name });
        } catch (Exception e) {
            e.printStackTrace();
        }

        return ret;
    }

	public static ParkingRecord getParkingByName(Context context, String name) {
		log("getParkingByAddr " + name);
		ContentResolver resolver = context.getContentResolver();
		ParkingRecord parking = null;
		Cursor cursor = null;
		try {
			cursor = resolver.query(Parking.CONTENT_URI, null, "name=?",
					new String[] { name },
					DEFAULT_SORT_ORDER);
		     if (cursor != null && cursor.moveToFirst())
		    	 parking = fromCursor(cursor);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		if (cursor != null)
		    cursor.close();

		return parking;
	}

	public static Cursor getAllParkings(Context context) {
		log("getAllParkings");
		ContentResolver resolver = context.getContentResolver();
		Cursor cursor = null;
		try {
			cursor = resolver.query(Parking.CONTENT_URI, null, null, null,
			        DEFAULT_SORT_ORDER);
			if (cursor != null && cursor.moveToFirst()) {
				return cursor;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return null;
	}

	public static ParkingRecord fromCursor(Cursor c) {
		ParkingRecord record = new ParkingRecord();
		record.longitude = c.getFloat(c.getColumnIndex(Parking.COLUMN_LONGITUDE));
		record.latitude = c.getFloat(c.getColumnIndex(Parking.COLUMN_LATITUDE));
		record.addr = c.getString(c.getColumnIndex(Parking.COLUMN_ADDR));
		record.name = c.getString(c.getColumnIndex(Parking.COLUMN_NAME));
		record.id = c.getInt(c.getColumnIndex(Parking.COLUMN_OWN));
		return record;
	}

	private static ContentValues toContentValues(ParkingRecord parking) {
        ContentValues cv = new ContentValues();
        cv.put(Parking.COLUMN_LONGITUDE, parking.longitude);
        cv.put(Parking.COLUMN_LATITUDE, parking.latitude);
        cv.put(Parking.COLUMN_ADDR, parking.addr);
        cv.put(Parking.COLUMN_NAME, parking.name);
        cv.put(Parking.COLUMN_OWN, parking.id);
        return cv;
	}

	private static void log(String msg) {
		Log.i("ProviderHelper", msg);
	}
}
